package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.article.request.UserArticleQueryRequest;
import com.blog.cmrpersonalblog.dto.user.request.UserFollowRequest;
import com.blog.cmrpersonalblog.dto.user.request.UserPasswordUpdateRequest;
import com.blog.cmrpersonalblog.dto.user.request.UserProfileUpdateRequest;
import com.blog.cmrpersonalblog.dto.user.response.UserInteractionResponse;
import com.blog.cmrpersonalblog.dto.user.response.UserProfileResponse;
import com.blog.cmrpersonalblog.service.UserProfileService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户详情控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserProfileController {

    @Resource
    private UserProfileService userProfileService;

//    @Resource
//    private UnifiedFileUploadService unifiedFileUploadService;

    /**
     * 获取用户详情信息
     */
    @GetMapping("/{userId}/profile")
    public Result<UserProfileResponse> getUserProfile(@PathVariable Long userId) {
        try {
            Long currentUserId = null;
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }
            
            UserProfileResponse profile = userProfileService.getUserProfile(userId, currentUserId);
            if (profile == null) {
                return Result.error("用户不存在");
            }
            
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取用户详情失败", e);
            return Result.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询用户发布的文章
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @param status 文章状态（可选）
     * @param categoryId 分类ID（可选）
     * @param tagIds 标签ID列表（可选，用于精确筛选）
     * @param keyword 关键词搜索（可选）
     * @param orderBy 排序字段（默认publish_time）
     * @param orderDirection 排序方向（默认desc）
     * @return 分页文章列表，包含标签信息
     */
    @GetMapping("/{userId}/articles")
    public Result<IPage<UserProfileResponse.ArticleInfo>> getUserArticles(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) java.util.List<Long> tagIds,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "publish_time") String orderBy,
            @RequestParam(defaultValue = "desc") String orderDirection) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = null;
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }

            UserArticleQueryRequest query = new UserArticleQueryRequest();
            query.setUserId(userId);
            query.setCurrentUserId(currentUserId);
            query.setPage(page);
            query.setSize(size);
            query.setStatus(status);
            query.setCategoryId(categoryId);
            query.setTagIds(tagIds);
            query.setKeyword(keyword);
            query.setOrderBy(orderBy);
            query.setOrderDirection(orderDirection);

            IPage<UserProfileResponse.ArticleInfo> articles = userProfileService.getUserArticles(query);
            return Result.success(articles);
        } catch (Exception e) {
            log.error("查询用户文章失败", e);
            return Result.error("查询用户文章失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取用户文章展示列表（支持按最新或最热排序）
     * 用于向其他用户展示某个用户的文章
     *
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @param sortType 排序类型：latest-最新，hot-最热（默认latest）
     * @return 用户文章分页列表
     */
    @GetMapping("/{userId}/articles/showcase")
    public Result<IPage<UserProfileResponse.ArticleInfo>> getUserArticleShowcase(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "latest") String sortType) {
        try {
            IPage<UserProfileResponse.ArticleInfo> articles =
                userProfileService.getUserArticleShowcase(userId, page, size, sortType);
            return Result.success(articles);
        } catch (Exception e) {
            log.error("获取用户文章展示信息失败", e);
            return Result.error("获取用户文章展示信息失败：" + e.getMessage());
        }
    }

    /**
     * 关注/取消关注用户
     *
     * @param userId   被关注/取消关注的用户ID
     * @param request 关注请求（包含isFollow字段）
     * @return 操作结果消息
     */
    @PostMapping("/{userId}/follow")
    @SaCheckLogin
    public Result<String> followUser(@PathVariable Long userId, @RequestBody @Validated UserFollowRequest request) {
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();

            if (currentUserId.equals(userId)) {
                return Result.error("不能关注自己");
            }

            boolean success = userProfileService.followUser(currentUserId, userId, request.getIsFollow());
            if (success) {
                return Result.success(request.getIsFollow() ? "关注成功" : "取消关注成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("关注/取消关注用户失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户的详情信息
     */
    @GetMapping("/profile")
    @SaCheckLogin
    public Result<UserProfileResponse> getCurrentUserProfile() {
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();
            UserProfileResponse profile = userProfileService.getUserProfile(currentUserId, currentUserId);
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取当前用户详情失败", e);
            return Result.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 更新当前用户的个人信息
     */
    @PutMapping("/updateProfile")
    @SaCheckLogin
    public Result<String> updateCurrentUserProfile(@RequestBody @Validated UserProfileUpdateRequest updateRequest) {
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();
            log.info("用户更新个人信息: userId={}", currentUserId);

            boolean success = userProfileService.updateUserProfile(currentUserId, updateRequest);
            if (success) {
                return Result.success("个人信息更新成功");
            } else {
                return Result.error("个人信息更新失败");
            }
        } catch (Exception e) {
            log.error("更新个人信息失败: userId={}, error={}", StpUtil.getLoginIdAsLong(), e.getMessage());
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 修改当前用户密码
     */
    @PutMapping("/password")
    @SaCheckLogin
    public Result<String> updateCurrentUserPassword(@RequestBody @Validated UserPasswordUpdateRequest passwordRequest) {
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();
            log.info("用户修改密码: userId={}", currentUserId);

            boolean success = userProfileService.updateUserPassword(currentUserId, passwordRequest);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            log.error("修改密码失败: userId={}, error={}", StpUtil.getLoginIdAsLong(), e.getMessage());
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取用户粉丝列表
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @return 粉丝分页列表
     */
    @GetMapping("/{userId}/followers")
    public Result<IPage<UserInteractionResponse.FollowerUserInfo>> getUserFollowers(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Long currentUserId = null;
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }

            IPage<UserInteractionResponse.FollowerUserInfo> followers =
                userProfileService.getUserFollowers(userId, currentUserId, page, size);
            return Result.success(followers);
        } catch (Exception e) {
            log.error("获取用户粉丝列表失败: userId={}", userId, e);
            return Result.error("获取粉丝列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取用户关注列表
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @return 关注用户分页列表
     */
    @GetMapping("/{userId}/following")
    public Result<IPage<UserInteractionResponse.FollowingUserInfo>> getUserFollowing(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Long currentUserId = null;
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }

            IPage<UserInteractionResponse.FollowingUserInfo> following =
                userProfileService.getUserFollowing(userId, currentUserId, page, size);
            return Result.success(following);
        } catch (Exception e) {
            log.error("获取用户关注列表失败: userId={}", userId, e);
            return Result.error("获取关注列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取用户点赞的文章列表
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @return 点赞文章分页列表
     */
    @GetMapping("/{userId}/liked-articles")
    public Result<IPage<UserInteractionResponse.LikedArticleInfo>> getUserLikedArticles(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            IPage<UserInteractionResponse.LikedArticleInfo> likedArticles =
                userProfileService.getUserLikedArticles(userId, page, size);
            return Result.success(likedArticles);
        } catch (Exception e) {
            log.error("获取用户点赞文章列表失败: userId={}", userId, e);
            return Result.error("获取点赞文章列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取用户收藏的文章列表
     * @param userId 用户ID
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @return 收藏文章分页列表
     */
    @GetMapping("/{userId}/collected-articles")
    public Result<IPage<UserInteractionResponse.CollectedArticleInfo>> getUserCollectedArticles(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            IPage<UserInteractionResponse.CollectedArticleInfo> collectedArticles =
                userProfileService.getUserCollectedArticles(userId, page, size);
            return Result.success(collectedArticles);
        } catch (Exception e) {
            log.error("获取用户收藏文章列表失败: userId={}", userId, e);
            return Result.error("获取收藏文章列表失败：" + e.getMessage());
        }
    }
}
